#include "mainwindow.h"
#include <QVBoxLayout>
#include <DTitlebar>
#include <DFileDialog>
#include <DWidgetUtil>
#include <QDir>
#include <QDebug>
#include <QtConcurrent/QtConcurrent>
#include <DWaterProgress>
#include "tabbutton.h"
#include <QDesktopServices>
#include <QProcessEnvironment>
#include <QSvgRenderer>
#include <QGuiApplication>
#include <QScreen>
#include <QApplication>
#include <DDialog>
#include <QMimeDatabase>
#include "donation/donation.h"
#include <DPlatformWindowHandle>
#define MIN_W 440
#define MIN_H 550

DWIDGET_USE_NAMESPACE
Widget::Widget(DMainWindow *parent)
    : DMainWindow(parent)
{

    //初始化环境变量
    app_path=QProcessEnvironment::systemEnvironment().value("XDG_DATA_HOME")+"/appimages/";
    desktop_path=QProcessEnvironment::systemEnvironment().value("XDG_DATA_HOME")+"/applications/";
    conf_path=QProcessEnvironment::systemEnvironment().value("XDG_CONFIG_HOME")+"/appimage-installer/";
    QList<QScreen*> screens = QApplication::screens();
    QScreen* screen = screens[0];
    qreal dp = screen->logicalDotsPerInch();
    //计算dpi对应的缩放比例
    dpi = dp/96.0;
    QDir dir("/");
    dir.mkpath(app_path);
    dir.mkpath(desktop_path);

    initUI();
    initConnect();
    setAcceptDrops(true);
    uninstall();
    setWindowTitle(QString::number(dpi));



    //初始化文件目录
    QDir data=QDir(QProcessEnvironment::systemEnvironment().value("XDG_DATA_HOME"));
    data.mkpath("appimages/icons");
    QDir conf=QDir(QProcessEnvironment::systemEnvironment().value("XDG_CONFIG_HOME"));
    conf.mkpath("appimage-installer");


    //判断UOS开发者模式是否启动
    QFile devMode("/var/lib/deepin/developer-mode/enabled");
    devMode.open(QFile::ReadOnly);
    QString dev(devMode.readAll());
    setWindowTitle(dev);
    if(!Dtk::Core::DSysInfo::isCommunityEdition()){
        if(dev.left(1)!="1"){
            lb_Title->setText(tr("Warring"));
            StackWidget->setCurrentIndex(5);
        }
        action_donation->setVisible(false); //UOS专业版关闭捐赠接口
    }
    //是否显示捐赠按钮
    QFile showDonation(conf_path+"showDonation");
    if(showDonation.open(QFile::ReadOnly)){
        int s=showDonation.readAll().toInt();
        if(s==0){
            action_donation->setVisible(false);
        }
    }

}

Widget::~Widget()
{

}

void Widget::open(QString path)
{
    openFile(path);
}
void Widget::initUI()
{
    //设置最外层窗口的基本属性
    titlebar()->setTitle("");
    titlebar()->setIcon(QIcon::fromTheme("appimage-installer"));
    titlebar()->setBackgroundTransparent(true);
    setTitlebarShadowEnabled(false);
    setMinimumSize(MIN_W,MIN_H);
    setMaximumSize(MIN_W,MIN_H);
    moveToCenter(this);

    DPlatformWindowHandle *handle=new DPlatformWindowHandle(this);
    handle->setShadowColor(QColor(0,0,0,60));	//修改阴影颜色，最后一项为alpha通道

    //预设
    QFont font_title;
    font_title.setBold(true);
    font_title.setPointSize(18);

    //创建一个窗口主体
    lb_Title->setFont(font_title);
    lb_Title->setAlignment(Qt::AlignCenter);
    setCentralWidget(mainwidget);
    QVBoxLayout *mainlayout=new QVBoxLayout;
    mainwidget->setLayout(mainlayout);
    mainlayout->addWidget(lb_Title);
    mainlayout->addWidget(StackWidget);

    StackWidget->insertWidget(0,page1);
    StackWidget->insertWidget(1,page2);
    StackWidget->insertWidget(2,page3);
    StackWidget->insertWidget(3,page4);
    StackWidget->insertWidget(4,page5);
    StackWidget->insertWidget(5,page6);


    //初始化首页
    StackWidget->setCurrentIndex(0);
    lb_Title->setText(tr("Please open the AppImage"));

    //初始化菜单
    this->titlebar()->setMenu(menu);
    menu->addMenu(menu_opendir);
    menu_opendir->addAction(action_app);
    menu_opendir->addAction(action_desktop);
    menu_opendir->setTitle(tr("Open folder"));
    action_app->setText(tr("Software folder"));
    action_desktop->setText(tr("Shortcut folder"));
    action_donation=new QAction;
    action_donation->setText(tr("Donation"));
    menu->addAction(action_donation);
    connect(action_donation,&QAction::triggered,[=](){
        DDialog dlg;
        QHBoxLayout *layout1=new QHBoxLayout;
        dlg.setLayout(layout1);
        layout1->setMargin(0);
        Donation *donation=new Donation(&dlg);
        layout1->addWidget(donation);
        dlg.setFixedSize(500,500);
        donation->setFixedSize(500,500);
        connect(donation,&Donation::offDonation,[=](bool a){
            action_donation->setVisible(!a);
            QFile f(conf_path+"showDonation");
            f.open(QFile::WriteOnly);
            QByteArray b;
            if(!a){
                //显示
                b.setNum(1);
            }else {
                //不显示
                b.setNum(0);
            }
            f.write(b);
        });
        dlg.exec();
    });



    /***************************PAGE6***************************/
    QVBoxLayout *page6_layout=new QVBoxLayout;
    page6->setLayout(page6_layout);
    QLabel* lb_icon=new QLabel;
    lb_icon->setPixmap(QIcon::fromTheme("dialog-error").pixmap(int(128.0*dpi),int(128.0*dpi)));
    lb_icon->setAlignment(Qt::AlignCenter);
    QLabel* lb=new QLabel;
    lb->setText(tr("It is detected that your operating system is UOS and \"Developer Mode\" is not turned on. Due to the limitation of UOS security mechanism, you cannot run any unsigned applications without turning on \"Developer Mode\" , Therefore, you will not be able to install other apps using this program. "));
    lb->setAlignment(Qt::AlignVCenter);
    lb->setWordWrap(true);
    page6_layout->addWidget(lb_icon);
    page6_layout->addWidget(lb);



    //预设
    QFont font_tip1;
    font_tip1.setPointSize(12);


    /***************************PAGE1***************************/

    DLabel *lb_OpenFile=new DLabel;
    DLabel *lb_Tips1=new DLabel;
    DLabel *lb_Line=new DLabel;
    QVBoxLayout *page1_layout=new QVBoxLayout;


    lb_OpenFile->setPixmap(QIcon::fromTheme("package-x-generic").pixmap(int(128.0*dpi),int(128.0*dpi)));
    lb_OpenFile->setAlignment(Qt::AlignCenter);

    lb_Tips1->setText(tr("Please drag the file here\nOr"));
    lb_Tips1->setAlignment(Qt::AlignCenter);
    lb_Tips1->setFont(font_tip1);
    QPalette plt;
    plt.setColor(QPalette::WindowText,QColor(150,150,150));
    lb_Tips1->setPalette(plt);

    lb_Line->setText("- - - - - - - - - - - - - - - - - - - -");
    lb_Line->setAlignment(Qt::AlignCenter);
    lb_Line->setFont(font_tip1);
    lb_Line->setPalette(plt);

    btn_OpenFile->setText(tr("Click here to open the file"));
    btn_OpenFile->setStyleSheet("border:0px;color:#1367EC");
    btn_OpenFile->setFocusPolicy(Qt::NoFocus);

    //布局

    page1_layout->addSpacing(70);
    page1_layout->addWidget(lb_OpenFile);
    page1_layout->addWidget(lb_Tips1);
    page1_layout->addWidget(lb_Line);
    page1_layout->addWidget(btn_OpenFile);


    page1_layout->addStretch();
    page1->setLayout(page1_layout);

    /***************************PAGE2***************************/

    DWaterProgress *m_water=new DWaterProgress;
    QVBoxLayout *page2_layout=new QVBoxLayout;

    m_water->setValue(50);
    m_water->setTextVisible(false);
    m_water->setFixedSize(90,90);
    m_water->start();

    page2_layout->setAlignment(Qt::AlignCenter);
    page2_layout->addWidget(m_water);
    page2_layout->addSpacing(20);

    page2->setLayout(page2_layout);
    /***************************PAGE3***************************/
    QVBoxLayout *page3_layout=new QVBoxLayout;
    QVBoxLayout *icon_pagefile_layout=new QVBoxLayout;
    QVBoxLayout *icon_pagetheme_layout=new QVBoxLayout;
    DLabel *lb_tip_theme=new DLabel;

    DLabel *lb_Line2=new DLabel;
    page3->setLayout(page3_layout);
    page3_layout->addSpacing(10);
    page3_layout->addWidget(tb_Tab);
    page3_layout->addSpacing(15);
    QHBoxLayout* icon_center_layout=new QHBoxLayout;
    icon_center_layout->addStretch();
    icon_center_layout->addWidget(sw_icon);
    icon_center_layout->addStretch();
    page3_layout->addLayout(icon_center_layout);
    page3_layout->setAlignment(Qt::AlignCenter);
    sw_icon->insertWidget(0,icon_page_file);
    sw_icon->insertWidget(1,icon_page_theme);
    icon_page_file->setLayout(icon_pagefile_layout);
    icon_page_theme->setLayout(icon_pagetheme_layout);
    icon_pagefile_layout->setAlignment(Qt::AlignCenter);
    icon_pagetheme_layout->setAlignment(Qt::AlignCenter);
    sw_icon->setFixedHeight(250);
    //page1
    icon_pagefile_layout->addWidget(lb_icon_file);
    lb_icon_file->setFixedHeight(128);
    lb_icon_file->setPixmap(QIcon::fromTheme("application-x-desktop").pixmap(int(128.0*dpi),int(128.0*dpi)));
    lb_icon_file->setAlignment(Qt::AlignCenter);

    lb_tip_file->setText(tr("Drag the icon file here\nOr"));
    lb_tip_file->setAlignment(Qt::AlignCenter);
    lb_tip_file->setFont(font_tip1);
    lb_tip_file->setPalette(plt);
    lb_tip_file->setWordWrap(true);
    btn_OpenIcon->setStyleSheet("border:0px;color:#1367EC");
    icon_pagefile_layout->addWidget(lb_tip_file);

    lb_Line2->setText("- - - - - - - - - - - - - - - - - - - -");
    lb_Line2->setAlignment(Qt::AlignCenter);
    lb_Line2->setFont(font_tip1);
    lb_Line2->setPalette(plt);
    icon_pagefile_layout->addWidget(lb_Line2);

    btn_OpenIcon->setText(tr("Click here to select the icon"));
    btn_OpenIcon->setFocusPolicy(Qt::NoFocus);

    icon_pagefile_layout->addWidget(btn_OpenIcon);
    icon_pagefile_layout->addStretch();
    //page2
    icon_pagetheme_layout->addWidget(lb_icon_theme);
    lb_icon_theme->setPixmap(QIcon::fromTheme("application-x-desktop").pixmap(int(128.0*dpi),int(128.0*dpi)));
    lb_icon_theme->setAlignment(Qt::AlignCenter);
    lb_icon_theme->setFixedHeight(128);
    ed_theme->setToolTip(tr("For example:\"gimp\""));
    icon_pagetheme_layout->addSpacing(8);
    QHBoxLayout* ed_layout=new QHBoxLayout;
    ed_layout->addStretch();
    ed_layout->addWidget(ed_theme);
    ed_layout->addStretch();
    icon_pagetheme_layout->addLayout(ed_layout);

    lb_tip_theme->setText(tr("Please enter an icon name"));
    lb_tip_theme->setAlignment(Qt::AlignCenter);
    lb_tip_theme->setFont(font_tip1);

    lb_tip_theme->setPalette(plt);
    icon_pagetheme_layout->addWidget(lb_tip_theme);
    icon_pagetheme_layout->addStretch();
    page3_layout->addStretch();
    QWidget *btn_next = new QWidget;
    QHBoxLayout *btn_layout = new QHBoxLayout;
    btn_next->setLayout(btn_layout);
    btn_layout->addStretch();
    btn_layout->addWidget(btn_iconToname);
    btn_iconToname->setFixedWidth(320);
    btn_layout->addStretch();
    btn_iconToname->setEnabled(false);
    page3_layout->addWidget(btn_next);

    btn_iconToname->setText(tr("Next"));
    page3_layout->addSpacing(14);
    ed_theme->setFixedWidth(200);
    /***************************PAGE4***************************/

    QVBoxLayout *page4_layout=new QVBoxLayout;
    page4->setLayout(page4_layout);
    page4_layout->addSpacing(20);
    page4_layout->addWidget(lb_icon_page4);
    page4_layout->setAlignment(Qt::AlignCenter);
    lb_icon_page4->setAlignment(Qt::AlignCenter);
    page4_layout->addSpacing(10);
    page4_layout->setSpacing(0);
    page4_layout->setContentsMargins(8,8,8,0);

    QWidget *appname = new QWidget;
    QHBoxLayout *appname_layout=new QHBoxLayout;
    appname->setLayout(appname_layout);
    appname_layout->addStretch();
    appname_layout->addWidget(ed_appname);
    appname_layout->addStretch();
    page4_layout->addWidget(appname);
    ed_appname->setFixedWidth(200);
    ed_appname->setPlaceholderText(tr("Name"));

    lb_icon_page4->setPixmap(QIcon::fromTheme("application-x-desktop").pixmap(int(128.0*dpi),int(128.0*dpi)));
    lb_icon_page4->setFixedHeight(128);

    page4_layout->addSpacing(8);

    DLabel *lb_tip_type=new DLabel;
    lb_tip_type->setText(tr("Software classification"));
    lb_tip_type->setAlignment(Qt::AlignCenter);
    lb_tip_type->setFont(font_tip1);
    setPalette(plt);
    page4_layout->addWidget(lb_tip_type);

    QWidget *apptype=new QWidget;
    QHBoxLayout *apptype_layout=new QHBoxLayout;
    apptype->setLayout(apptype_layout);
    apptype_layout->addStretch();
    apptype_layout->addWidget(cbb_type);
    apptype_layout->addStretch();
    page4_layout->addWidget(apptype);
    cbb_type->setFixedWidth(200);
    cbb_type->addItem(tr("Internet"),"Network");
    cbb_type->addItem(tr("Chat"),"Chat");
    cbb_type->addItem(tr("Music"),"Audio");
    cbb_type->addItem(tr("Video"),"AudioVideo");
    cbb_type->addItem(tr("Graphics"),"Graphics");
    cbb_type->addItem(tr("Game"),"Game");
    cbb_type->addItem(tr("Office"),"Office");
    cbb_type->addItem(tr("Reading"),"Translation");
    cbb_type->addItem(tr("Development"),"Development");
    cbb_type->addItem(tr("System"),"System");
    cbb_type->addItem(tr("Other"),"");
    cbb_type->setCurrentText(tr("Other"));//设置默认选项位于其他选项

    page4_layout->addStretch();

    QWidget *btn_finish_widget= new QWidget;
    QHBoxLayout *btn_finish_layout = new QHBoxLayout;
    btn_finish_layout->setMargin(0);
    btn_finish_widget->setLayout(btn_finish_layout);
    btn_finish_layout->addStretch();
    btn_finish_layout->addWidget(btn_finish);
    btn_finish->setFixedWidth(320);
    btn_finish_layout->addStretch();
    btn_finish->setText(tr("Install"));
    btn_finish->setEnabled(false);

    QWidget *cb_widget= new QWidget;
    QHBoxLayout *cb_layout = new QHBoxLayout;
    cb_widget->setLayout(cb_layout);
    cb_layout->addStretch();
    cb_layout->addWidget(cb_parameter);
    cb_layout->addStretch();
    page4_layout->addWidget(cb_widget);



    cb_parameter->setText(tr("--no-sandbox parameter"));
    page4_layout->addWidget(btn_finish_widget);
    page4_layout->addSpacing(8);
    page4_layout->addWidget(btn_back);

    btn_back->setFocusPolicy(Qt::NoFocus);
    QFont font_back;
    font_back.setPointSize(10);
    btn_back->setText(tr("Back"));
    btn_back->setFont(font_back);
    btn_back->setFixedHeight(15);
    page4_layout->addSpacing(8);

    /***************************PAGE5***************************/

    QVBoxLayout *page5_layout=new QVBoxLayout;

    m_water2->setValue(50);
    m_water2->setTextVisible(false);
    m_water2->setFixedSize(90,90);
    m_water2->start();

    page5_layout->setAlignment(Qt::AlignCenter);
    page5_layout->addWidget(m_water2);

    lb_Finish->setPixmap(QIcon::fromTheme("dialog-ok").pixmap(int(128.0*dpi),int(128.0*dpi)));
    lb_Finish->setAlignment(Qt::AlignCenter);
    page5_layout->addWidget(lb_Finish);
    lb_Finish->hide();
    page5_layout->addSpacing(20);
    page5->setLayout(page5_layout);

    updateTheme();//防止出现主题出现问题的情况

    return;
}

void Widget::initConnect()
{
    connect(DGuiApplicationHelper::instance(),&DGuiApplicationHelper::themeTypeChanged,this,&Widget::updateTheme);

    connect(btn_OpenFile,&DPushButton::clicked,[=](){Widget::openFile();});
    connect(btn_OpenIcon,&DPushButton::clicked,[=](){Widget::openIcon();});
    //菜单
    connect(action_app,&QAction::triggered,[=](){QDesktopServices::openUrl(QUrl(app_path));});
    connect(action_desktop,&QAction::triggered,[=](){QDesktopServices::openUrl(QUrl(desktop_path));});

    connect(tb_Tab,&TabButton::indexChange,[=](int i){
        sw_icon->setCurrentIndex(i);
        if(i==0){
            if(iconPath==""){
                btn_iconToname->setEnabled(false);
            }else {
                btn_iconToname->setEnabled(true);
            }

        }else {
            if(!QIcon::fromTheme(ed_theme->text()).pixmap(int(128.0*dpi),int(128.0*dpi)).isNull()){
                btn_iconToname->setEnabled(true);
            }else {
                btn_iconToname->setEnabled(false);
            }
        }
    });
    connect(ed_theme,&DLineEdit::textChanged,lb_icon_theme,[=](QString name){
        if(!QIcon::fromTheme(name).pixmap(int(128.0*dpi),int(128.0*dpi)).isNull()){
            lb_icon_theme->setPixmap(QIcon::fromTheme(name).pixmap(int(128.0*dpi),int(128.0*dpi)));
            btn_iconToname->setEnabled(true);
        }else{
            lb_icon_theme->setPixmap(QIcon::fromTheme("application-x-desktop").pixmap(int(128.0*dpi),int(128.0*dpi)));
            if(tb_Tab->index==1){
                btn_iconToname->setEnabled(false);
            }
        }

    });
    connect(btn_iconToname,&DPushButton::clicked,[=](){
       lb_Title->setText(tr("Please enter the software name"));
       StackWidget->setCurrentIndex(3);
       if(tb_Tab->index==0){
           theIcon=iconPath;
           lb_icon_page4->setPixmap(*lb_icon_file->pixmap());
       }else {
           if(!lb_icon_theme->pixmap()->isNull()){
               theIcon=ed_theme->text();
               lb_icon_page4->setPixmap(*lb_icon_theme->pixmap());
           }
       }

       qDebug()<<theIcon;

    });
    connect(btn_finish,&DPushButton::clicked,this,&Widget::install);
    connect(ed_appname,&QLineEdit::textChanged,[=](){
        if(ed_appname->text()!=""){
            btn_finish->setEnabled(true);
            theName=ed_appname->text();
        }else {
            btn_finish->setEnabled(false);
        }
    });
    connect(btn_back,&DPushButton::clicked,[=](){
        StackWidget->setCurrentIndex(StackWidget->currentIndex()-1);
        lb_Title->setText(tr("Select the program icon"));
    });
}

void Widget::uninstall() //用来删除已经被卸载的程序
{
    QDir dir(app_path);   //QDir的路径一定要是全路径，相对路径会有错误

    if(!dir.exists())
        return;

    //取到所有的文件和文件名，去掉.和..文件夹
    dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
    dir.setSorting(QDir::DirsFirst);
    //将其转化为一个list
    QFileInfoList list = dir.entryInfoList();
    if(list.size()<1)
        return;

    int i = 0;
    //采用递归算法
    do {
        QFileInfo fileInfo = list[i];
        if(!fileInfo.isDir()){
            QString appimage_file=fileInfo.filePath();
            if(appimage_file.right(9)==".AppImage" || appimage_file.right(9)==".appimage" || appimage_file.right(9)==".Appimage"){

                QDir dir2(desktop_path);   //QDir的路径一定要是全路径，相对路径会有错误

                if(!dir2.exists())
                    return;

                //取到所有的文件和文件名，去掉.和..文件夹
                dir2.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
                dir2.setSorting(QDir::DirsFirst);
                //将其转化为一个list
                QFileInfoList list2 = dir2.entryInfoList();
                if(list2.size()<1)
                    return;

                int j = 0;
                //采用递归算法
                bool isNormal=false;
                QStringList tmp_desktop_list;
                do {
                    QFileInfo fileInfo2 = list2[j];
                    if(!fileInfo2.isDir()){
                        QString desktop_file=fileInfo2.filePath();
                        if(desktop_file.right(8)==".desktop"){
                            QSettings desktop_ini(desktop_file,QSettings::IniFormat);
                            tmp_desktop_list=desktop_ini.value("Desktop Entry/Exec").toUrl().toString().split(" ");
                            qDebug()<<appimage_file<<tmp_desktop_list[0];
                            if(appimage_file==tmp_desktop_list[0]){
                                isNormal=true;
                                break;
                            }
                        }
                    }

                    ++j;
                }while(j<list2.size());
                if(!isNormal){
                    qDebug()<<"Remove:"<<appimage_file;
                    QFile::remove(appimage_file);
                }
            }

        }
        ++i;
    }while(i<list.size());

}

void Widget::updateTheme()
{
    if(!(DGuiApplicationHelper::instance()->themeType()==DGuiApplicationHelper::DarkType)){
        //亮色模式
        QPalette palette(this->palette());
        palette.setColor(QPalette::Background, QColor("#FFFFFF"));
        this->setPalette(palette);
        btn_back->setStyleSheet("border:0px;color:#B7BFCD");

        tb_Tab->setTheme(false,Dtk::Gui::DGuiApplicationHelper::instance()->applicationPalette().highlight().color());

        lb_Title->setStyleSheet("color:#414D68");
    }else {
        //黑色模式
        QPalette palette(this->palette());
        palette.setColor(QPalette::Background, QColor("#282828"));
        this->setPalette(palette);
        btn_back->setStyleSheet("border:0px;color:#464E51");
        lb_Title->setStyleSheet("color:#C0C6D4");
        tb_Tab->setTheme(true,Dtk::Gui::DGuiApplicationHelper::instance()->applicationPalette().highlight().color());
    }
}

void Widget::install()
{
    StackWidget->setCurrentIndex(4);
    lb_Title->setText(tr("Installing"));
    QtConcurrent::run([=](){

        QDir data=QDir(QProcessEnvironment::systemEnvironment().value("XDG_DATA_HOME"));
        data.mkpath("appimages/icons");

        QFile appimage(filePath);
        QFileInfo appinfo(filePath);
        appimage.copy(app_path+appinfo.fileName());
        filePath=app_path+appinfo.fileName();
        filePath="\""+filePath+"\"";
        QProcess chmod;
        chmod.start("chmod +x "+app_path+appinfo.fileName());
        chmod.waitForFinished();

        if(tb_Tab->index==0){
            QFile icon(iconPath);
            QFileInfo iconinfo(iconPath);
            icon.copy(app_path+"/icons/"+iconinfo.fileName());
            theIcon=app_path+"/icons/"+iconinfo.fileName();
        }

        QFile desktop_file(desktop_path+theName+".desktop");
        desktop_file.open(QIODevice::WriteOnly | QIODevice::Text);
        QString desktoptext;
        desktoptext+="[Desktop Entry]\n";
        desktoptext+="Name = "+theName+"\n";
        desktoptext+="Icon = "+theIcon+"\n";
        if(cb_parameter->isChecked()){
            desktoptext+="Exec = "+filePath+" --no-sandbox\n";
        }else {
            desktoptext+="Exec = "+filePath+"\n";
        }

        desktoptext+="Type = Application\n";
        desktoptext+="Categories = "+cbb_type->itemData(cbb_type->currentIndex()).toString();

        desktop_file.write(desktoptext.toUtf8());
        desktop_file.close();
        m_water2->hide();
        lb_Finish->show();
        lb_Title->setText(tr("Installation is complete"));
    });


}

void Widget::dragEnterEvent(QDragEnterEvent *event)
{
    QMimeDatabase db;
    qDebug()<<db.mimeTypeForFile(event->mimeData()->text()).name();
    if(StackWidget->currentIndex()==0){
        //打开appimage
        if(db.mimeTypeForFile(event->mimeData()->text()).name().left(11)=="application")
        {
            event->acceptProposedAction();
        }
    }else if(StackWidget->currentIndex()==2 && sw_icon->currentIndex()==0){
        //打开图标
        if(db.mimeTypeForFile(event->mimeData()->text()).name()=="image/svg+xml" ||
                db.mimeTypeForFile(event->mimeData()->text()).name()=="image/png")
        {
            event->acceptProposedAction();
        }
    }

}

void Widget::dropEvent(QDropEvent *event)
{
    QString path;
    path=event->mimeData()->urls()[0].path();
    if(StackWidget->currentIndex()==0){
        openFile(path);
    }else {
        openIcon(path);
    }

    qDebug()<<event->mimeData()->text();
}

void Widget::openFile()
{
    openFile(fileDialog->getOpenFileUrl(this,tr("Open file"),QDir::home().path(),"AppImage(*.appimage)").path());

}
void Widget::openFile(QString path)
{

    if(!path.isEmpty()){
        qDebug()<<path;
        filePath=path;
        appfile->setFilename(filePath);
        QtConcurrent::run([=](){
           QDir tmp=QDir::tempPath()+"/appimage-installer/squashfs-root";
           tmp.removeRecursively();
           appfile->load();

           if(!tmp.isEmpty()){
               tb_Tab->setIndex(0);
           }else {
               tb_Tab->setIndex(1);
           }


           //自动获取图标
           QProcess lspng;
           lspng.start("ls "+QDir::tempPath()+"/appimage-installer/squashfs-root");
           lspng.waitForFinished();
           QStringList fileicon = QString::fromUtf8(lspng.readAllStandardOutput()).split("\n");
           for(int i = 0;i<fileicon.size();i++){
               if (fileicon[i].right(4)==".png") {
                   openIcon(QDir::tempPath()+"/appimage-installer/squashfs-root/"+fileicon[i]);
                   break;
               }
               if (fileicon[i].right(4)==".svg") {
                   openIcon(QDir::tempPath()+"/appimage-installer/squashfs-root/"+fileicon[i]);
                   break;
               }
           }

           if(appfile->isdefault()){
               if(!QIcon::fromTheme(appfile->themeicon).isNull()){
                   tb_Tab->setIndex(1);
//                   lb_icon_theme->setPixmap(QIcon::fromTheme(appfile->themeicon).pixmap(128,128));
                   ed_theme->setText(appfile->themeicon);
               }
               ed_appname->setText(appfile->name);

               cbb_type->setCurrentText(tr(appfile->type.left(appfile->type.length()-1).toUtf8()));
           }
           StackWidget->setCurrentIndex(2);
           lb_Title->setText(tr("Select the program icon"));


        });
        StackWidget->setCurrentIndex(1);
        lb_Title->setText(tr("Loading"));

    }
}

void Widget::openIcon()
{
    QDir tmp_pkg=QDir(QDir::tempPath()+"/appimage-installer/squashfs-root");
    if(tmp_pkg.isEmpty()){
        openIcon(fileDialog->getOpenFileUrl(this,tr("Open file"),QDir::homePath(),"Icon(*.svg *.png)").path());
        return;
    }
    openIcon(fileDialog->getOpenFileUrl(this,tr("Open file"),QDir::tempPath()+"/appimage-installer/squashfs-root","Icon(*.svg *.png)").path());
}

void Widget::openIcon(QString path)
{

    if(!path.isEmpty()){
        iconPath=path;
        lb_tip_file->setText(iconPath);
        QMimeDatabase db;
        if(db.mimeTypeForFile(iconPath).name()=="image/png"){
            QPixmap icon;
            QImage img_icon;
            img_icon.load(iconPath);
            icon=QPixmap::fromImage( img_icon.scaled(QSize(128,128),Qt::KeepAspectRatio,Qt::SmoothTransformation));
            btn_iconToname->setEnabled(true);
            lb_icon_file->setPixmap(icon);
        }
        if(db.mimeTypeForFile(iconPath).name()=="image/svg+xml"){
            QSvgRenderer* svgRender = new QSvgRenderer();
            svgRender->load(iconPath);

            QPixmap* pixmap = new QPixmap(128,128);
            pixmap->fill(Qt::transparent);//设置背景透明
            QPainter p(pixmap);
            svgRender->render(&p);
            btn_iconToname->setEnabled(true);
            lb_icon_file->setPixmap(*pixmap);


        }
    }
}

